<?php
/**
 * 支付控制器，余额、平安银行、通联
 * Created by PhpStorm.
 * User: John
 * Date: 17-1-19
 * Time: 下午6:55
 */
namespace app\backend\controller;

use app\backend\controller\traits\IncomeNoticeList;
use app\backend\model\Lease;
use Business\CMBC\CmbcSDK;
use think\Controller;
use app\backend\model\BillManager;
use app\backend\model\Member;
use app\backend\model\JournalOnline;
use Cache\Redis;
use Business\TongLian\TongLianPay;
use Business\Fuyou\Fuyou;

class PayController extends Controller
{
    use IncomeNoticeList;
    private $_memberId = null;
    private $_dtype    = null;
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
    }

    /**
     * 账户余额支付
     * @date   2017-01-19
     * @author Lanlc
     *
     * @param  string  $orderNum         订单号
     * @param  int     $mid              缴费用户ID
     * @param  int     $beginCycle       账单开始时间
     * @param  int     $endCycle         账单结束时间
     * @param  int     $payMoney         总额
     * @param  int     $type             缴费类型：1租赁账单，2托管账单
     * @param  array   $orderId          订单id数组
     *
     * @return array
     */
    public function payByBalance()
    {
        $orderNum   = I('post.order_num', '', 'strval');
        $mid        = I('post.mid', '', 'intval');
        $beginCycle = I('post.begin_cycle', '', 'intval');
        $endCycle   = I('post.end_cycle', '', 'intval');
        $payMoney   = I('post.money', '', 'floatval');
        $type       = I('post.type', '', 'intval');
        $orderId    = I('post.order_id');
        $orderId    = json_decode($orderId, true);
        //$orderNum = '149500801179';$beginCycle='20150604';$endCycle='20150614';$mid=87;$orderId=[3769, 3770];$payMoney=1000;$type=1;
        if (!$orderNum || !$mid || !$beginCycle || !$endCycle || !$orderId || !is_array($orderId)) {
            $this->apiReturn(202, [], '缺少参数');
        }

        if ($this->_memberId != $mid) {
            $this->apiReturn(201, [], '当前登录账号非缴费人');
        }

        $payMoney      = fen($payMoney);
        $billModel     = new BillManager();
        $redis         = new Redis();
        $payLog = [
            'order_num'   => $orderNum,
            'mid'         => $mid,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'money'       => $payMoney,
            'type'        => $type,
            'order_id'    => $orderId,
        ];

        if ($type == 1) {
            $key   = $orderNum.$beginCycle.$endCycle.$type;
            if ($redis->get($key)) {
                $this->apiReturn(209, [], '系统正在处理中，请30秒后重试');
            }

            $redis->set($key, '1', 30);
            //获取这个用户应付账单的id
            $idArr = $billModel->getBillDetailByOwner($this->_memberId, $this->_dtype, $orderNum, $beginCycle, $endCycle, 0, 'id');
            if (!$idArr) {
                $redis->rm($key);
                $this->apiReturn(202, [], '找不到对应账单');
            }
            $orderArray = array_column($idArr, 'id');
            //判断所传账单id数组是否在该用户的应收id里
            foreach ($orderId as $id) {
                if (!in_array($id, $orderArray)) {
                    $redis->rm($key);
                    $this->apiReturn(203, [], '账单id有误');
                }
            }

            $map   = ['id' => ['in', $orderId], 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle];
            //获取该订单应付总额
            $backendMoney = $billModel->getPayBillCntByOrderNum($orderNum, $map);

            if ($backendMoney != $payMoney) {
                $redis->rm($key);
                $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
            }

            $memberModel = new Member();
            $memberMoney = $memberModel->getMemberMoney($this->_memberId);
            if ($backendMoney > $memberMoney) {
                $redis->rm($key);
                $this->apiReturn(203, [], '账户余额不足，请先充值或选择其他支付方式');
            }

            $field = 'id, money, owner_id, tenant_id, type_money';
            $orderData = $billModel->getPayBillByOrderNum($orderNum, $field, $map);

            if ($orderData) {
                //新增支付log
                zft_log('ready_to_pay/balance', json_encode($payLog));
                //收款消息队列
                $incomeNotice = [];
                foreach ($orderData as $key => $val) {
                    //付款方减钱
                    $resDesc = $memberModel->modifyMemberMoney($this->_memberId, $val['owner_id'], 0, $val['money'], 1, 1,$val['id'], $orderNum, $val['type_money'], 0, 0, $beginCycle, $endCycle);

                    if ($resDesc['code'] == 200) {
                        //设置订单为已支付状态
                        $updateRes = $billModel->updatePayBill(['id' => $val['id']], ['status' => 1]);
                        if (!$updateRes) {
                            zft_log('set_paybill_fail', print_r($billModel->getLastSql(), true));
                        }
                        //收方加钱
                        $resAsc = $memberModel->modifyMemberMoney($val['owner_id'], $this->_memberId, 0, $val['money'], 0, 1,$val['id'], $orderNum, $val['type_money'], 0, 0, $beginCycle, $endCycle);
                        $tmp = [//基本的付款信息
                            'mid'         => $val['owner_id'],//收款人
                            'payer_id'    => $this->_memberId,//付款人
                            'begin_cycle' => $beginCycle,
                            'end_cycle'   => $endCycle,
                            'money'       => $val['money'],
                            'ordernum'    => $orderNum,
                            'type_money'  => $val['type_money'],
                        ];
                        array_push($incomeNotice, $tmp);
                        if ($resAsc['code'] != 200) {
                            zft_log('modifyMemberMoney', print_r($resAsc['msg'], true));
                        }
                    } else {
                        zft_log('modifyMemberMoney', print_r($resDesc['msg'], true));
                    }
                }
                //新增至消息队列
                if ($this->addIncomeNotice($incomeNotice, $orderNum, $this->_memberId)) {
                    //获取未发送的短信列表
                    $smsList = $this->getIncomeNotice($orderNum, $beginCycle, $endCycle, 1, 0, 0);
                    if ($smsList) {//发送短信
                        //获取对应的房号
                        $leaseModel = new Lease();
                        $roomArr = $leaseModel->getLeaseExtByOrderNum($orderNum, 'room');
                        $roomArr = array_column($roomArr, 'room');

                        $idArr = $this->sendSms($smsList, $roomArr);
                        if ($idArr) {//更新这些id的状态
                            $this->updateSendStatus($idArr, 1, time());
                        }
                    }
                }
                $redis->rm($key);
                $this->apiReturn(200, [], '缴费成功');
            } else {
                $redis->rm($key);
                $this->apiReturn(201, [], '缴费账单不存在');
            }
        } elseif ($type == 2) {
            $key   = $orderNum.$beginCycle.$endCycle.$type;
            if ($redis->get($key)) {
                $this->apiReturn(209, [], 'locking');
            }
            $redis->set($key, '1', 30);

            $map   = ['ordernum' => $orderNum, 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle,'is_delete' => 0];
            $field = 'should_rent-share_money as money, owner_id, id';
            //获取该订单应付总额
            $trustBillInfo = $billModel->getTrustBill($map, $field);
            if (!$trustBillInfo) {
                $redis->rm($key);
                $this->apiReturn(206, [], '账单不存在');
            }
            $trustBillInfo = $trustBillInfo[0];
            $backendMoney = $trustBillInfo['money'];

            if ($backendMoney != $payMoney) {
                $redis->rm($key);
                $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
            }

            $memberModel = new Member();
            $memberMoney = $memberModel->getMemberMoney($this->_memberId);
            if ($backendMoney > $memberMoney) {
                $redis->rm($key);
                $this->apiReturn(203, [], '账户余额不足，请先充值或选择其他支付方式');
            }

            //新增支付log
            zft_log('ready_to_pay/balance', json_encode($payLog));

            //支付方减钱
            $resDesc = $memberModel->modifyMemberMoney($this->_memberId, $trustBillInfo['owner_id'], 0, $backendMoney, 1, 1,$trustBillInfo['id'], $orderNum, 9, 0, 0, $beginCycle, $endCycle);

            if ($resDesc['code'] == 200) {
                //设置订单为已支付状态
                $updateRes = $billModel->updateTrustBill(['id' => $trustBillInfo['id']], ['status' => 1]);
                if (!$updateRes) {
                    zft_log('set_trustBill_fail', print_r($billModel->getLastSql(), true));
                }
                //收款方加钱
                $resAsc = $memberModel->modifyMemberMoney($trustBillInfo['owner_id'], $this->_memberId, 0, $backendMoney, 0, 1, $trustBillInfo['id'], $orderNum, 9, 0, 0, $beginCycle, $endCycle);
                if ($resAsc['code'] != 200) {
                    zft_log('modifyMemberMoney', print_r($resAsc['msg'], true));
                }
            } else {
                zft_log('modifyMemberMoney', print_r($resDesc['msg'], true));
            }
            $redis->rm($key);
            $this->apiReturn(200, [], '缴费成功');
        } else {
            $this->apiReturn(202, [], '非法参数');
        }
    }


    /**
     * 富有银行支付检测
     * @date   2017-04-26
     * @author wuhao
     *
     * @param  string  $orderNum         订单号
     * @param  int     $mid              缴费用户ID
     * @param  int     $beginCycle       账单开始时间
     * @param  int     $endCycle         账单结束时间
     * @param  int     $payMoney         总额
     * @param  int     $type             缴费账单类型：1租赁，2托管
     * @param  string  $bankType         银行代码
     * @param  int     $payType          支付类型 0=B2C 1=B2B
     * @param  string  $url              同步回调
     * @param  array   $orderId          应付账单id数组
     *
     * @return json
     */
    public function payByFuYouCheck()
    {
        $orderNum   = I('order_num', '', 'strval');     //订单号
        $mid        = I('mid', '', 'intval');            //缴费用户ID
        $beginCycle = I('begin_cycle', '', 'intval');   //账单开始时间
        $endCycle   = I('end_cycle', '', 'intval');     //账单结束时间
        $payMoney   = I('money', '', 'floatval');       //总额(元)
        $type       = I('type', '', 'intval');                //缴费账单类型：1租赁，2托管
        $bankType   = I('bank_type', '', 'strval');          //银行代码
        $url        = I('url', '', 'strval');                 //同步通知地址
        $payType    = I('pay_type', 0, 'intval');        //支付类型 0=B2C 1=B2B
        $orderId    = I('order_id');
        $orderId    = json_decode($orderId, true);

//        $orderNum = '149308464024';
//        $mid = 87;
//        $beginCycle= '20170424';
//        $endCycle = '20170523';
//        $payMoney = 0.01;
//        $type = 1;
//        $bankType = '0000000000';
//        $url = 'www.louxiaomei.com';

        if (!$orderNum || !$mid || !$beginCycle || !$endCycle || !$bankType) {
            $this->apiReturn(202, [], '缺少参数');
        }

        if ($this->_memberId != $mid) {
            $this->apiReturn(202, [], '当前登录账号非缴费人');
        }
        if (!in_array($payType, [0, 1])) {
            $this->apiReturn(202, [], '支付方式有误');
        }
        $redis = new Redis();
        $key = $orderNum.$beginCycle.$endCycle.'fuyou'.$bankType;
        if ($redis->get($key)) {
            $this->apiReturn(205, [], '系统正在处理中，请30秒后重试');
        }
        $redis->set($key, '1', 30);

        $payMoney = fen($payMoney);
        $billModel = new BillManager();
        if ($type == 1) {
            //获取这个用户应付账单的id
            $idArr = $billModel->getBillDetailByOwner($this->_memberId, $this->_dtype, $orderNum, $beginCycle, $endCycle, 0, 'id');
            if (!$idArr) {
                $redis->rm($key);
                $this->apiReturn(207, [], '要缴费的账单不存在');
            }

            $orderArray = array_column($idArr, 'id');

            //判断所传账单id数组是否在该用户的应收id里
            foreach ($orderId as $key => $id) {
                if (!in_array($id, $orderArray)) {
                    $redis->rm($key);
                    $this->apiReturn(207, [], '账单id有误');
                }
                $orderId[$key] = intval($id);
            }

            $map   = ['id' => ['in', $orderId], 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle];
            //获取该订单应付总额
            $backendMoney = $billModel->getPayBillCntByOrderNum($orderNum, $map);
            if (!$backendMoney) {
                $redis->rm($key);
                $this->apiReturn(207, [], '要缴费的账单不存在');
            }

            if ($backendMoney != $payMoney) {
                $redis->rm($key);
                $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
            }
        } else {
            $map   = ['ordernum' => $orderNum, 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle,'is_delete' => 0];
            $field = 'should_rent-share_money as money, owner_id, id';

            //获取该订单应付总额
            $trustBillInfo = $billModel->getTrustBill($map, $field);
            if (!$trustBillInfo) {
                $redis->rm($key);
                $this->apiReturn(206, [], '要缴费的账单不存在');
            }

            $trustBillInfo = $trustBillInfo[0];
            $backendMoney = $trustBillInfo['money'];

            if ($backendMoney != $payMoney) {
                $redis->rm($key);
                 $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
            }
        }

        $this->apiReturn(200, [], '');
    }

    /**
     * 富有银行支付
     * @date   2017-04-26
     * @author wuhao
     *
     * @param  string  $orderNum         订单号
     * @param  int     $mid              缴费用户ID
     * @param  int     $beginCycle       账单开始时间
     * @param  int     $endCycle         账单结束时间
     * @param  int     $payMoney         总额
     * @param  int     $type             缴费账单类型：1租赁，2托管
     * @param  string  $bankType         银行代码
     * @param  string  $url              同步回调地址
     * @param  int     $payType          支付类型 0=B2C 1=B2B
     * @param  array   $orderId          账单id数组
     *
     * @return json
     */
    public function payByFuYou()
    {
        $orderNum   = I('order_num', '', 'strval');     //订单号
        $mid        = I('mid', '', 'intval');           //缴费用户ID
        $beginCycle = I('begin_cycle', '', 'intval');   //账单开始时间
        $endCycle   = I('end_cycle', '', 'intval');     //账单结束时间
        $payMoney   = I('money', '', 'floatval');       //总额(元)
        $type       = I('type', '', 'intval');          //缴费账单类型：1租赁，2托管
        $bankType   = I('bank_type', '', 'strval');     //银行代码
        $url        = I('url', '', 'strval');           //同步通知地址
        $payType    = I('pay_type', 0, 'intval');        //支付类型 0=B2C 1=B2B
        $orderId    = I('order_id');
        $orderId    = json_decode($orderId, true);
        //$orderId=[3694];
//        $orderNum = '149308464024';
//        $mid = 87;
//        $beginCycle= '20170424';
//        $endCycle = '20170523';
//        $payMoney = 0.01;
//        $type = 1;
//        $bankType = '0000000000';
//        $url = 'www.louxiaomei.com';

        if (!$orderNum || !$mid || !$beginCycle || !$endCycle || !$bankType) {
            echo '缺少参数';
            die;
        }

        if ($this->_memberId != $mid) {
            echo '当前登录账号非缴费人';
            die;
        }
        if (!in_array($payType, [0, 1])) {
            echo '支付方式有误';
            die;
        }

        $payMoney = fen($payMoney);
        $billModel = new BillManager();
        if ($type == 1) {
            //获取这个用户应付账单的id
            $idArr = $billModel->getBillDetailByOwner($this->_memberId, $this->_dtype, $orderNum, $beginCycle, $endCycle, 0, 'id');
            if (!$idArr) {
                echo '要缴费的账单不存在';
                die;
            }
            $orderArray = array_column($idArr, 'id');
            //判断所传账单id数组是否在该用户的应收id里

            foreach ($orderId as $key => $id) {
                if (!in_array($id, $orderArray)) {
                    echo '账单id有误';
                    die;
                }
                $orderId[$key] = intval($id);
            }

            $map   = ['id' => ['in', $orderId], 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle];
            //获取该订单应付总额
            $backendMoney = $billModel->getPayBillCntByOrderNum($orderNum, $map);
            if (!$backendMoney) {
                echo '要缴费的账单不存在';
                die;
            }

            if ($backendMoney != $payMoney) {
                echo '缴费数额有出入，请刷新重试';
                die;
            }
        } else {
            $map   = ['ordernum' => $orderNum, 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle,'is_delete' => 0];
            $field = 'should_rent-share_money as money, owner_id, id';

            //获取该订单应付总额
            $trustBillInfo = $billModel->getTrustBill($map, $field);
            if (!$trustBillInfo) {
                echo '要缴费的账单不存在';
                die;
            }

            $trustBillInfo = $trustBillInfo[0];
            $backendMoney = $trustBillInfo['money'];

            if ($backendMoney != $payMoney) {
                echo '缴费数额有出入，请刷新重试';
                die;
            }
        }

        //增加在线支付交易记录
        $journalOnlineModel = new JournalOnline();
        if ($payType == 0) {//B2C
            $source = 1;
        } else {//B2B
            $source = 4;
        }

        $tempOrder = $orderNum;
        $serialNumber = $tempOrder.getMillisecond().$type;
        //$orderNum .= $beginCycle.$endCycle.$type;
        $orderIdJson = json_encode($orderId);

        $journalOnlineModel->setAllProperty($orderNum, $orderIdJson, $serialNumber, 'fuyou', $this->_memberId, '', $payMoney, '', time(), $source, 0, $type, $beginCycle, $endCycle);
        $check = $journalOnlineModel->chkOnlineRec();
        if (!$check) {
            $addRes = $journalOnlineModel->addRecord();
            if (!$addRes) {
                zft_log('addOnlineRecord', print_r($journalOnlineModel->getLastSql(), true));
                echo '服务器异常';
                die;
            }
        } else {
            //有记录的话先删除以前的
            $id = $check['id'];
            //$journalOnlineModel->deleteById($id);
            //再添加
            $addRes = $journalOnlineModel->addRecord();
            if (!$addRes) {
                zft_log('addOnlineRecord', print_r($journalOnlineModel->getLastSql(), true));
                $this->apiReturn(203, [], '服务器异常');
            }
        }

        //新增支付log
        $payLog = [
            'order_num'   => $orderNum,
            'serial_num'  => $serialNumber,
            'mid'         => $mid,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'money'       => $payMoney,
            'type'        => $type,
            'bank_type'   => $bankType,
            'pay_type'    => $payType
        ];
        zft_log('ready_to_pay/fuyou', json_encode($payLog));

        $fuYou = new Fuyou();
        $fuYou->pay($serialNumber, $payMoney, $bankType, $url, $payType);
    }



    /**
     * 通联支付方式
     * @date   2017-02-15
     * @author Lanlc
     *
     * @param  string  $orderNum         订单号
     * @param  int     $mid              缴费用户ID
     * @param  int     $beginCycle       账单开始时间
     * @param  int     $endCycle         账单结束时间
     * @param  int     $payMoney         总额
     * @param  int     $orderType        账单类型：1租赁，2托管
     * @param  int     $payType          支付类型：1支付宝，2微信
     * @param  array   $orderId          要支付的账单id数组
     *
     * @return json
     */
    public function payByTongLian()
    {
        $orderNum   = I('post.order_num', '', 'strval');
        $mid        = I('post.mid', '', 'intval');
        $beginCycle = I('post.begin_cycle', '', 'intval');
        $endCycle   = I('post.end_cycle', '', 'intval');
        $payMoney   = I('post.money', '', 'floatval');
        $orderType  = I('post.order_type', '', 'intval');
        $payType    = I('post.pay_type', '', 'intval');
        $orderId    = I('post.order_id');
        $orderId    = json_decode($orderId, true);
        //$orderId=[3692, 3833, 3834];
        if (!$orderNum || !$mid || !$beginCycle || !$endCycle ||!$orderId || !is_array($orderId)) {
            $this->apiReturn(206, [], '缺少参数');
        }

        if ($this->_memberId != $mid) {
            $this->apiReturn(206, [], '当前登录账号非缴费人');
        }

        $redis = new Redis();
        $key = $orderNum.$beginCycle.$endCycle.$payType.'tonglian';
        if ($redis->get($key)) {
            $this->apiReturn(205, [], '系统正在处理中，请30秒后重试');
        }

        $redis->set($key, '1', 30);
        $payMoney = fen($payMoney);

        $billModel = new BillManager();

        if (strlen($orderNum) != 12) {
            $redis->rm($key);
            $this->apiReturn(204, [], '订单号异常');
        }


        if ($orderType == 1) {
            //获取这个用户应付账单的id
            $idArr = $billModel->getBillDetailByOwner($this->_memberId, $this->_dtype, $orderNum, $beginCycle, $endCycle, 0, 'id');
            if (!$idArr) {
                $redis->rm($key);
                $this->apiReturn(202, [], '找不到对应账单');
            }
            $orderArray = array_column($idArr, 'id');
            //判断所传账单id数组是否在该用户的应收id里
            foreach ($orderId as $key => $id) {
                if (!in_array($id, $orderArray)) {
                    $redis->rm($key);
                    $this->apiReturn(207, [], '账单id有误');
                }
                $orderId[$key] = intval($id);
            }

            $map   = ['id' => ['in', $orderId], 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle];
            //获取该订单应付总额
            $backendMoney = $billModel->getPayBillCntByOrderNum($orderNum, $map);
            if (!$backendMoney) {
                $redis->rm($key);
                $this->apiReturn(207, [], '要缴费的账单不存在');
            }

            if ($backendMoney != $payMoney) {
                $redis->rm($key);
                $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
            }
        } else {
            $map   = ['ordernum' => $orderNum, 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle,'is_delete' => 0];
            $field = 'should_rent-share_money as money, owner_id, id';

            //获取该订单应付总额
            $trustBillInfo = $billModel->getTrustBill($map, $field);
            if (!$trustBillInfo) {
                $redis->rm($key);
                $this->apiReturn(206, [], '要缴费的账单不存在');
            }

            $trustBillInfo = $trustBillInfo[0];
            $backendMoney = $trustBillInfo['money'];
            if ($backendMoney != $payMoney) {
                $redis->rm($key);
                $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
            }
        }

        if ($payType == 1) {//通联支付宝
            $payType = 'A01';
            $source  = 2;
        } else {//通联微信
            $payType = 'W01';
            $source  = 3;
        }

        //合同编号+账单起始周期+账单结束周期+账单类型 刚好32位
        //由于对方的接口问题，得重新组织订单规则：12位订单+账单起始周期+账单结束周期+账单类型+3位随机数
        $serialNumber = $orderNum.$beginCycle.$endCycle.$orderType.genRandomNum(3);
        $journalOnlineModel = new JournalOnline();
        $orderIdJson = json_encode($orderId);

        $journalOnlineModel->setAllProperty($orderNum, $orderIdJson, $serialNumber, 'TongLian', $this->_memberId, '', $payMoney, '', time(), $source, 0, $orderType, $beginCycle, $endCycle);
        $check = $journalOnlineModel->chkOnlineRec();
        if (!$check) {
            $addRes = $journalOnlineModel->addRecord();
            if (!$addRes) {
                zft_log('addOnlineRecord', print_r($journalOnlineModel->getLastSql(), true));
                $redis->rm($key);
                $this->apiReturn(203, [], '服务器异常');
            }
        } else {
            //有记录的话先删除以前的
            $id = $check['id'];
            //$journalOnlineModel->deleteById($id);
            //再添加
            $addRes = $journalOnlineModel->addRecord();
            if (!$addRes) {
                zft_log('addOnlineRecord', print_r($journalOnlineModel->getLastSql(), true));
                $redis->rm($key);
                $this->apiReturn(203, [], '服务器异常');
            }
        }

        $tongLian = new TongLianPay();

        $randomstr = time();
        $body = '商品名称';
        $remark= 'zftPay';

        //新增支付log
        $payLog = [
            'order_num'   => $orderNum,
            'serial_num'  => $serialNumber,
            'mid'         => $mid,
            'begin_cycle' => $beginCycle,
            'end_cycle'   => $endCycle,
            'money'       => $payMoney,
            'type'        => $orderType,
            'pay_type'    => $payType,
        ];

        zft_log('ready_to_pay/tongLian', json_encode($payLog));

        $payResult = $tongLian->pay($payMoney, $serialNumber, $payType, $randomstr, $body, $remark);
        if (isset($payResult['retcode']) && $payResult['retcode'] == 'SUCCESS') {
            $redis->rm($key);
            $this->apiReturn(200, ['url' => $payResult['payinfo']], '');
        } else {
            $redis->rm($key);
            $this->apiReturn(202, [], $payResult['retmsg']);
        }
    }

    /**
     * 民生支付
     * @date   2017-06-12
     * @author wuhao
     *
     * @param  string  $orderNum         订单号
     * @param  int     $mid              缴费用户ID
     * @param  int     $beginCycle       账单开始时间
     * @param  int     $endCycle         账单结束时间
     * @param  int     $payMoney         总额
     * @param  int     $orderType        账单类型：1租赁，2托管
     * @param  int     $payType          支付类型：1支付宝，2微信
     * @param  array   $orderId          要支付的账单id数组
     *
     * @return json
     */
//    public function payByCmbc()
//    {
//        $orderNum   = I('post.order_num', '', 'strval');
//        $mid        = I('post.mid', '', 'intval');
//        $beginCycle = I('post.begin_cycle', '', 'intval');
//        $endCycle   = I('post.end_cycle', '', 'intval');
//        $payMoney   = I('post.money', '', 'floatval');
//        $orderType  = I('post.order_type', '', 'intval');
//        $payType    = I('post.pay_type', '', 'intval');
//        $orderId    = I('post.order_id');
//        $orderId    = json_decode($orderId, true);
//        if ($this->_memberId != 117) {
//            $this->apiReturn(206, [], '此接口已关闭，请稍后重试');
//        }
//       /* $orderNum='149500801179';
//        $mid=87;
//        $beginCycle='20160715';$endCycle='20160814';$payMoney=3061.8;$orderId = [3704];$orderType=1;$payType=1;*/
//        $notifyUrl = MAIN_DOMAIN.'r/AlipayNotify_cmbcNotify';
//
//        if (!$orderNum || !$mid || !$beginCycle || !$endCycle ||!$orderId || !is_array($orderId)) {
//            $this->apiReturn(206, [], '缺少参数');
//        }
//
//        if ($this->_memberId != $mid) {
//            $this->apiReturn(206, [], '当前登录账号非缴费人');
//        }
//
//        $redis = new Redis();
//        $key = $orderNum.$beginCycle.$endCycle.$payType.'minsheng';
///*        if ($redis->get($key)) {
//            $this->apiReturn(205, [], '系统正在处理中，请30秒后重试');
//        }*/
//
//        $redis->set($key, '1', 30);
//        $payMoney = fen($payMoney);
//        $billModel = new BillManager();
//
//        if (strlen($orderNum) != 12) {
//            $redis->rm($key);
//            $this->apiReturn(204, [], '订单号异常');
//        }
//        if ($orderType == 1) {
//            //获取这个用户应付账单的id
//            $idArr = $billModel->getBillDetailByOwner($this->_memberId, $this->_dtype, $orderNum, $beginCycle, $endCycle, 0, 'id');
//            if (!$idArr) {
//                $redis->rm($key);
//                $this->apiReturn(202, [], '找不到对应账单');
//            }
//            $orderArray = array_column($idArr, 'id');
//            //判断所传账单id数组是否在该用户的应收id里
//            foreach ($orderId as $key => $id) {
//                if (!in_array($id, $orderArray)) {
//                    $redis->rm($key);
//                    $this->apiReturn(207, [], '账单id有误');
//                }
//                $orderId[$key] = intval($id);
//            }
//
//            $map   = ['id' => ['in', $orderId], 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle];
//            //获取该订单应付总额
//            $backendMoney = $billModel->getPayBillCntByOrderNum($orderNum, $map);
//            if (!$backendMoney) {
//                $redis->rm($key);
//                $this->apiReturn(207, [], '要缴费的账单不存在');
//            }
//
//            if ($backendMoney != $payMoney) {
//                $redis->rm($key);
//                $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
//            }
//        } else {
//            $map   = ['ordernum' => $orderNum, 'tenant_id' => $this->_memberId, 'status' => 0, 'begin_cycle' => $beginCycle,'end_cycle' => $endCycle,'is_delete' => 0];
//            $field = 'should_rent-share_money as money, owner_id, id';
//
//            //获取该订单应付总额
//            $trustBillInfo = $billModel->getTrustBill($map, $field);
//            if (!$trustBillInfo) {
//                $redis->rm($key);
//                $this->apiReturn(206, [], '要缴费的账单不存在');
//            }
//
//            $trustBillInfo = $trustBillInfo[0];
//            $backendMoney = $trustBillInfo['money'];
//            if ($backendMoney != $payMoney) {
//                $redis->rm($key);
//                $this->apiReturn(202, [], '缴费数额有出入，请刷新重试');
//            }
//        }
//
//        if ($payType == 1) {//民生支付宝
//            $selectTradeType = 'API_ZFBQRCODE';
//            $source  = 5;
//            $prefix  = 'A';
//        } else {//民生微信
//            $selectTradeType = 'API_WXQRCODE';
//            $source  = 6;
//            $prefix = 'B';
//        }
//
//        $serialNumber = $prefix.$orderNum.$beginCycle.$endCycle.$orderType.genRandomNum(4);
//        $journalOnlineModel = new JournalOnline();
//        $orderIdJson = json_encode($orderId);
//
//        $journalOnlineModel->setAllProperty($orderNum, $orderIdJson, $serialNumber, 'Minsheng', $this->_memberId, '', $payMoney, '', time(), $source, 0, $orderType, $beginCycle, $endCycle);
//        $check = $journalOnlineModel->chkOnlineRec();
//        if (!$check) {
//            $addRes = $journalOnlineModel->addRecord();
//            if (!$addRes) {
//                zft_log('addOnlineRecord', print_r($journalOnlineModel->getLastSql(), true));
//                $redis->rm($key);
//                $this->apiReturn(203, [], '服务器异常');
//            }
//        } else {
//            //有记录的话先删除以前的
//            $id = $check['id'];
//            $journalOnlineModel->deleteById($id);
//            //再添加
//            $addRes = $journalOnlineModel->addRecord();
//            if (!$addRes) {
//                zft_log('addOnlineRecord', print_r($journalOnlineModel->getLastSql(), true));
//                $redis->rm($key);
//                $this->apiReturn(203, [], '服务器异常');
//            }
//        }
//
//        $minSheng = new CmbcSDK();
//
//        //新增支付log
//        $payLog = [
//            'order_num'   => $orderNum,
//            'serial_num'  => $serialNumber,
//            'mid'         => $mid,
//            'begin_cycle' => $beginCycle,
//            'end_cycle'   => $endCycle,
//            'money'       => $payMoney,
//            'type'        => $orderType,
//            'pay_type'    => $payType,
//        ];
//
//        zft_log('ready_to_pay/cmbc', json_encode($payLog));
//
//        $payResult = $minSheng->Pay($payMoney, $orderNum, $serialNumber,$notifyUrl, '租付通账单支付', $selectTradeType);
//        if (isset($payResult['return_code']) && $payResult['return_code'] == 'SUCCESS') {
//            $redis->rm($key);
//            $this->apiReturn(200, ['url' => $payResult['code_url']], '');
//        } else {
//            $redis->rm($key);
//            $this->apiReturn(202, [], $payResult['return_msg']);
//        }
//    }

}
